package
{
	import flash.display.*;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	import org.flashbrighton.as3bots.bots.*;
	import org.flashbrighton.as3bots.controllers.GameController;
	import org.flashbrighton.as3bots.display.LoadBotPage;
	import org.flashbrighton.as3bots.models.GameModel;
	import org.flashbrighton.as3bots.views.GameView;
	import org.flashbrighton.as3bots.views.ui.Message;
	
	
	[SWF(width="800", height="550", frameRate="30", backgroundColor="#333333")]
	public class Main extends Sprite
	{
		[Embed(source = "/../assets/gradius.ttf", fontName = "Gradius", mimeType = "application/x-font-truetype", embedAsCFF = "false")]
		private var GradiusFont:Class;
		
		[Embed(source = "/../assets/Arkitech.ttf", fontName = "Arkitech", mimeType = "application/x-font-truetype", embedAsCFF = "false")]
		private var EvaFont:Class;
		
		private var _model:GameModel;
		private var _controller:GameController;
		private var _view:GameView;
		
		
		protected var botLibrary : Vector.<BaseBot>;
		protected var bots : Vector.<BaseBot>;
		protected var botLoadPage : LoadBotPage;

		public function Main()
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
			initBotLoader();
		}
		
		
		protected function initBotLoader():void
		{
			botLibrary = new Vector.<BaseBot>( [new DummyBot] );
			bots = new Vector.<BaseBot>;
			botLoadPage = new LoadBotPage( botLibrary, bots );
			botLoadPage.addEventListener( Event.COMPLETE , handleBotLoadPageComplete );
			addChild( botLoadPage );
		}
		
		
		public function addBots():void
		{
			for each( var bot : BaseBot in bots )
			{
				_controller.addBot( bot );
			}
		}
		
		
		private function init(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			setStage();
		}
		
		
		private function initGame(e:Event):void
		{
			setGame();
			addBots();
			setupGame();
			initKeyboard();
		}
		
		
		private function setStage():void
		{
			stage.align = StageAlign.TOP_LEFT;
		}
		
		
		private function setGame():void
		{
			_model = new GameModel();
			_view = new GameView(_model);
			_controller = new GameController(_model, _view);
			
			addChild(_view);
		}

		
		private function setupGame():void
		{
			_controller.setupGame();
		}
		

 		private function initKeyboard():void
 		{
 			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			Message.write("* SPACE = START/PAUSE *");
 		}
		
		
 		private function onKeyDown(k:KeyboardEvent):void
 		{
 			switch (k.keyCode)
 			{
 				case Keyboard.SPACE:
 				if (!_model.started)
				{
					_controller.startGame();
				}
				else if (_model.isPlaying)
				{
					_controller.pauseGame();
				}
				else
				{
					_controller.resumeGame();
				}
 				break;
 			}
 		}
		
		
 		protected function handleBotLoadPageComplete( e:Event ):void
 		{
 			removeChild( botLoadPage );
 			initGame( e );
 		}

	}
	
}
